<template>
  <div>
    <h3>训练计划同步</h3>
    <div class="body">
      <vxe-toolbar style="height: 150px;">
        <template #buttons>
          <el-row type="flex" :gutter="20">
            <el-col :span="6">
              <el-input v-model="searchForm.name" size="small" style="width: 60%;" suffix-icon="el-icon-view" placeholder="输入文档标题"></el-input>
            </el-col>
            <el-col v-if="!docClassId" :span="4">
              <el-select  v-model="searchForm.docClassId" style="margin-left: 20px;" size="small" collapse-tags
                filterable clearable placeholder="选择文档类型">
                <el-option :label="item" :value="key" v-for="(item,key,index) in dict_available" :key="index">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="15">
              <sportChangesportItem ref="sport2sportItem" search="search" :sportChangesportItemData="sportChangesportItemData"
                @selectDataChange='searchSelectDataChange' title="撰写者" />
            </el-col>
          </el-row>
          <el-row  style="margin: 20px 0;" type="flex" justify="space-between" :gutter="20">
            <el-col :span="6" >
              <div>
                <el-button-group style="display: flex;">
                  <el-button type="success" icon="el-icon-printer" size="medium" @click="exportData">开始同步</el-button>
                  <el-button type="success" size="medium" @click="exportSelectEvent"> {{checkText}} <i class="el-icon-document-checked"></i></el-button>
                </el-button-group>
              </div>
            </el-col>
            <el-col :span="10">
              <el-date-picker size="small" v-model="doubleDate" type="daterange" align="center" unlink-panels style="width: 70%;"
                range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions">
              </el-date-picker>
            </el-col>
            <el-col :span="4" style="display: flex;">
              <el-button type="success" size="small" icon="el-icon-s-promotion" @click="searchSubmit"
                style="margin: 0 10px;">
                搜索</el-button>
              <vxe-button @click="clearTableFilter" status="warning" icon="el-icon-refresh-right"> 清空</vxe-button>
            </el-col>
            <el-col :span="5">
              <vxe-input style="float: right;" v-model.trim.lazy="filterName" type="search" placeholder="快捷检索"
                @input="searchEvent"></vxe-input>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="1">
              <h4>要同步给谁</h4>
            </el-col>
            <el-col :span="10">
              <sportChangesportItem ref="sport2sportItem" search="search" :sportChangesportItemData="sportChangesportItemData"
                @selectDataChange='searchSelectDataChange2' title="撰写者" />
            </el-col>
            <el-col :span="3">
              <el-input size="small" v-model="crossOrg" placeholder="crossOrg"></el-input>
            </el-col>
            <el-col :span="3">
              <el-input size="small" :disabled="crossOrg!='crossOrg'" v-model="targetForm.empId" placeholder="撰写者Id"></el-input>
            </el-col>
            <el-col :span="3">
              <el-input size="small" v-model="targetBeginDate" placeholder="目标开始时间"></el-input>
            </el-col>
            <el-col :span="3">
              <el-button type="success" icon="el-icon-printer" size="medium" @click="copyTargetBeginDate">按时间同步</el-button>
            </el-col>
          </el-row>
        </template>
      </vxe-toolbar>
      <vxe-table resizable ref="XTable" border max-height="600" stripe highlight-hover-row highlight-current-row resizable
        :loading="loading" :data="dataList" @sort-change="sortChange" :export-config="{}">
        <vxe-column field="checkbox" type="checkbox" width="60"></vxe-column>
        <vxe-table-column field="name" title="文档标题" sortable min-width="250"></vxe-table-column>
        <vxe-table-column v-if="!docClassId" field="available" title="文档类型" sortable></vxe-table-column>
        <vxe-table-column v-if="docClassId" field="sport" title="运动项目" sortable></vxe-table-column>
        <vxe-table-column v-if="docClassId" field="sportItem" title="运动小项" sortable></vxe-table-column>
        <vxe-table-column  field="memoName" title="署名" sortable></vxe-table-column>
        <vxe-table-column field="emp" title="撰写者" sortable></vxe-table-column>
        <vxe-table-column field="createDate" title="创建日期" sortable></vxe-table-column>
        <vxe-table-column field="openDate" title="开始日期" sortable></vxe-table-column>
        <vxe-table-column field="closeDate" title="截止日期" sortable></vxe-table-column>
        <vxe-table-column field="status" title="状态" sortable width="70"></vxe-table-column>
      </vxe-table>
      <vxe-pager :loading="loading" :current-page="page.currentPage" :page-size="page.pageSize" :total="page.totalResult"
        :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']" @page-change="handlePageChange">
      </vxe-pager>
      <!-- 单个打印预览 -->
      <vxe-modal v-model="printModal" title="预览" height="80%" show-zoom resize width="600" show-footer>
        <template #default>
          <weekPlanPrint v-if="currentDocClassId==33||currentDocClassId==34" id="myPrint" :previewData="previewData" :docClassId="currentDocClassId" />
          <otherPlanPrint v-else  id="myPrint" :previewData="previewData" :docClassId="currentDocClassId" />
        </template>
        <template #footer>
          <el-button @click="printEvent" type="primary" icon="el-icon-printer" size="mini">打印</el-button>
          <el-button @click="downloadWord" type="primary" icon="iconfont icon-word1" size="mini"> 导出word</el-button>
        </template>
      </vxe-modal>
      <!-- 全部打印预览导出 -->
      <vxe-modal v-model="printWordModal" title="预览" height="80%" show-zoom resize width="600" show-footer>
        <template #default>
          <planWordPrint id="myPrint" :docDataWord="docDataWord" />
        </template>
        <template #footer>
          <el-button @click="printEvent" type="primary" icon="el-icon-printer" size="small">打印</el-button>
          <el-button @click="downloadWord" type="primary" icon="iconfont icon-word1" size="mini"> 导出word</el-button>
        </template>
      </vxe-modal>
    </div>
  </div>
</template>

<script>
  import {plan_doc_all,allType,plan_doc_delete,plan_doc_select,doc_copyAll,doc_copyAllByDate} from '@/api/plan.js'
  import {currentRoleEmployee} from '@/api/person.js'
  import {sport_by_org,sport_item,plan_doc_available} from '@/api/dict.js'
  import otherPlanPrint from "@/components/print/otherPlanPrint.vue"
  import weekPlanPrint from "@/components/print/weekPlanPrint.vue"
  import sportChangesportItem from '@/components/sport2sportItem/sport2sportItem.vue'
  import planWordPrint from '@/components/print/planWordPrint.vue'
  import htmlDocx from 'html-docx-js/dist/html-docx';
  import saveAs from 'file-saver';
  export default {
    components: {
      otherPlanPrint,
      weekPlanPrint,
      sportChangesportItem,
      planWordPrint,
    },
    data() {
      return {
        docClassId: null,
        pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            },
          },{
            text: '最近一年',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30 * 12);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
        defaultDataList: [],
        dataList: [],
        page: {
          currentPage: 1,
          pageSize: 10,
          totalResult: 0
        },
        loading: false,
        filterName: '',
        searchProps: [],
        dict_emp: {},
        dict_sport: {},
        dict_sportItem: {},
        dict_available: {},
        printModal: false,
        previewData: {},
        currentDocClassId: null,
        plan_path: {
          2:	'/trainPlan/viewPeriodPlan',
          26:	'/trainPlan/viewMultiYearPlan',
          27:	'/trainPlan/viewFullYearPlan',
          28:	'/trainPlan/viewWinterPeriodPlan',
          29:	'/trainPlan/viewWinterSummary',
          30:	'/trainPlan/viewPre_MatchPlan',
          31:	'/trainPlan/viewMatchScheme',
          32:	'/trainPlan/viewYearMatchSummary',
          33:	'/weekPlanCreateAndPreview',
          34:	'/classPlanCreateAndPreview',
          35:	'/trainPlan/viewFullYearSummary',
          36:	'/trainPlan/viewYearPaper',
          42:	'/trainPlan/viewMatchSummary',
          41:	'/plan/viewMorality',
        },
        searchForm: {
          docClassId: '33',
          name: null,
          empId: null,
          sportId: null,
          sportItemId: null,
          beginDate: null,
          endDate: null,
        },
        targetForm: {
          empId: null,
          sportId: null,
          sportItemId: null,
        },
        doubleDate: null,
        sportChangesportItemData: {},
        printWordModal: false,
        checkText: '选择同步',
        currentRow: {},
        search: false,
        crossOrg: '',
        targetBeginDate: ''
      }
    },
    created() {
      this.init_dict().then(()=>{
        this.searchSubmit()
      })
    },
    computed: {
      docmentVisibility() {
        return this.$store.state.app.docmentVisibility;
      },
    },
    watch: {
      filterName(val) {
        if(!val){
          this.page = {
          currentPage: 1,
          pageSize: 10,
          totalResult: 0,
          }
          this.search = false
          this.findList()
        }
      },
      docmentVisibility(newVal) {
        if (!newVal) return;
        this.getPlanList()
      },
    },
    methods: {
      exportData() {
        this.getDocDataIdAll()
      },
      exportSelectEvent() {
        if(this.checkText == '选择同步'){
          this.checkText = '取消选择'
          this.$refs.XTable.showColumn(this.$refs.XTable.getColumnByField('checkbox'))
        }else{
          this.checkText = '选择同步'
          this.$refs.XTable.clearCheckboxRow()
          this.$refs.XTable.hideColumn(this.$refs.XTable.getColumnByField('checkbox'))
        }
      },
      copyTargetBeginDate() {
        let docDataIdArr = []
        let data = this.$refs.XTable.getCheckboxRecords()
        if(data.length==0){
         this.defaultDataList.forEach(item=>{
           docDataIdArr.push(item.docDataId)
         })
        }else{
          data.forEach(item=>{
            docDataIdArr.push(item.docDataId)
          })
        }
        let json = {}
        json.docDataIds = docDataIdArr.join(',')
        json.targetEmpId = this.targetForm.empId
        if(this.crossOrg) json.crossOrg = this.crossOrg
        if(this.targetBeginDate) json.targetBeginDate = this.targetBeginDate
        doc_copyAllByDate(json).then(res=>{
          if(res.code === 200) {
            this.$message.success(res.data)
          }else{
            this.$message.error(res.message)
          }
        })
      },
      getDocDataIdAll() {
        let docDataIdArr = []
        let data = this.$refs.XTable.getCheckboxRecords()
        if(data.length==0){
         this.defaultDataList.forEach(item=>{
           docDataIdArr.push(item.docDataId)
         })
        }else{
          data.forEach(item=>{
            docDataIdArr.push(item.docDataId)
          })
        }
        let json = {}
        json.docDataIds = docDataIdArr.join(',')
        json.targetEmpId = this.targetForm.empId
        if(this.crossOrg) json.crossOrg = this.crossOrg
        doc_copyAll(json).then(res=>{
          if(res.code === 200) {
            this.$message.success(res.data)
          }else{
            this.$message.error(res.message)
          }
        })
      },
      searchSubmit() {
        this.loading = true
        let data = {}
        if(this.searchForm.docClassId) data.docClassId = this.searchForm.docClassId
        if(this.searchForm.empId) data.empId = this.searchForm.empId
        if(this.searchForm.name) data.name = this.searchForm.name
        if(this.searchForm.sportId) data.sportId = this.searchForm.sportId
        if(this.searchForm.sportItemId) data.sportItemId = this.searchForm.sportItemId
        if (this.doubleDate){
          data.beginDate = this.$moment(this.doubleDate[0]).format('YYYY-MM-DD') + ' 00:00:00'
          data.endDate = this.$moment(this.doubleDate[1]).format('YYYY-MM-DD') + ' 00:00:00'
        }
        plan_doc_select({data:data,docClassId:this.docClassId}).then(res=>{
          if(res.code === 200 && res.data.length != 0) {
            this.init_data(res.data)
            let sessionDocDataIds = []
            res.data.forEach(item=>{
              sessionDocDataIds.push(item)
            })
            window.localStorage.setItem('sessionDocDataIds',JSON.stringify(sessionDocDataIds))
          }else{
            this.defaultDataList = []
          }
        }).then(()=>{
          this.page.pageSize = this.defaultDataList.length
          this.$refs.XTable.hideColumn(this.$refs.XTable.getColumnByField('checkbox'))
          this.findList()
        })
      },
      clearTableFilter() {
        this.searchForm = {
          docClassId: null,
          name: null,
          empId: null,
          sportId: null,
          sportItemId: null,
          beginDate: null,
          endDate: null,
        }
        this.doubleDate = null
        this.sportChangesportItemData = {}
        this.getPlanList()
        window.localStorage.removeItem('sessionDocDataIds')
      },
      searchSelectDataChange({
        sportId,
        sportItemId,
        person
      }) {
        this.searchForm.sportId = sportId
        this.searchForm.empId = person
        this.searchForm.sportItemId = sportItemId
      },
      searchSelectDataChange2({
        sportId,
        sportItemId,
        person
      }) {
        this.targetForm.sportId = sportId
        this.targetForm.empId = person
        this.targetForm.sportItemId = sportItemId
      },
      planDelete(row) {
        this.$confirm('此操作将永久删除该条记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          plan_doc_delete({docDataId:row.docDataId}).then(res=>{
            if(res.code === 200) {
              this.$message.success('删除成功！')
              this.getPlanList()
            }else{
              this.$message.error(res.message)
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      planEdit(row) {
        let data = {
            path: this.plan_path[row.docClassId],
            query: {docDataId:row.docDataId}
        }
        if(row.parentId!=-1){
          data.query.parentId = row.parentId
        }
        const { href } = this.$router.resolve(data);
        window.open(href, '_blank');
      },
      downloadWord() {
        let data = this.$refs.XTable.getCheckboxRecords()
        let name = data.length!=0?data[0].name:this.currentRow.name
        setTimeout(()=>{
          const divEl = document.getElementById('myPrint')
          this.page = `<!DOCTYPE html><html><head><meta charset="UTF-8"></head><body>${divEl.innerHTML}</body></html>`
          const converted = htmlDocx.asBlob(this.page);
          // 用 FielSaver.js里的保存方法 进行输出
          saveAs(converted, name+'.docx');
        },500)
      },
      printEvent() {
        let data = this.$refs.XTable.getCheckboxRecords()
        if(data[0]){
          document.title = data[0].name
        }else{
          document.title = this.currentRow.name
        }
        setTimeout(()=>{
            const divEl = document.getElementById('myPrint')
            const printStyle = `
              p{
                margin: 4px 0;
              }
            `
            this.$XPrint({
              sheetName: '',
              style: printStyle,
              content: divEl.innerHTML
            })
        },200)
      },
      printModalShow(row) {
        this.currentRow = row
        this.currentDocClassId = row.docClassId
        allType({docDataId:row.docDataId,docClassId:row.docClassId}).then(res=>{
          if(res.code === 200) {
            this.previewData = res.data
            this.printModal = true
          }else{
            this.$message.error(res.message)
          }
        })
      },
      getPlanList() {
        this.loading = true
        plan_doc_all(this.docClassId).then(res=>{
         if(res.code === 200) {
            this.init_data(res.data)
         }else{
           this.defaultDataList = []
          this.$message.error(res.message)
         }
       }).then(()=>{
         this.findList()
         this.$refs.XTable.hideColumn(this.$refs.XTable.getColumnByField('checkbox'))
       })
      },
      init_data(data) {
        if(data.length==0) return
        data.forEach(item=>{
          item.emp = this.dict_emp[item.empId]
          item.available = this.dict_available[item.docClassId]
          item.sport = this.dict_sport[item.sportId]
          item.sportItem = this.dict_sportItem[item.sportItemId]
          item.createDate = this.$moment(item.createDate).format('YYYY-MM-DD')=='Invalid date'?'':this.$moment(item.createDate).format('YYYY-MM-DD')
          item.closeDate = this.$moment(item.closeDate).format('YYYY-MM-DD')=='Invalid date'?'':this.$moment(item.closeDate).format('YYYY-MM-DD')
          item.openDate = this.$moment(item.openDate).format('YYYY-MM-DD')=='Invalid date'?'':this.$moment(item.openDate).format('YYYY-MM-DD')
          item.status = item.statusId == 1 ? "正式" : "草稿"
          if(item.memo){
            let arr = item.memo.split(',')
            let memoArr = []
            arr.forEach(memo=>{
              memoArr.push(this.dict_emp[memo])
            })
            item.memoName = memoArr.join(',')
          }
        })
        if(data[0]){
          this.searchProps = Object.keys(data[0])
        }
        this.defaultDataList = data
      },
      init_dict() {
        return new Promise((resolve,reject)=>{
          currentRoleEmployee().then(res=>{
            res.data.forEach(item=>{
              this.dict_emp[item.empId] = item.name
            })
            sport_by_org().then(res=>{
              this.dict_sport = res
            })
            sport_item().then(res=>{
              this.dict_sportItem = res
            })
            plan_doc_available().then(res=>{
              this.dict_available = res
              resolve()
            })
          })
        })
      },
      searchEvent() {
        const filterName = this.$XEUtils.toValueString(this.filterName).trim().toLowerCase()
        if (filterName) {
          const filterRE = filterName
          const searchProps = this.searchProps
          const rest = this.defaultDataList.filter(item => searchProps.some(key => this.$XEUtils.toValueString(item[
            key]).toLowerCase().indexOf(filterName) > -1))
          this.dataList = rest.map(row => {
            const item = Object.assign({}, row)
            searchProps.forEach(key => {
              item[key] = this.$XEUtils.toValueString(item[key]).replace(filterRE, match => match)
            })
            return item
          })
          this.page = {
          	currentPage: 1,
          	pageSize: this.dataList.length,
          	totalResult: this.dataList.length
          }
          this.search = true
        } else {
          this.dataList = this.defaultDataList
     }
      },
      handlePageChange({
        currentPage,
        pageSize
      }) {
        this.page.currentPage = currentPage
        this.page.pageSize = pageSize
        this.findList()
      },
      sortChange() {
      	if(!this.search){
          this.page.currentPage = 1
      	  this.page.pageSize = this.defaultDataList.length
      	  this.findList()
      	}else{
      	  this.page.pageSize = this.dataList.length
      	}
      },
      findList() {
        this.loading = true
        setTimeout(() => {
          if(this.insertSuccess){
            this.page.totalResult = this.defaultDataList.length
            this.page.currentPage = Math.ceil(this.page.totalResult/this.page.pageSize)
            this.dataList = this.defaultDataList.slice((this.page.currentPage - 1) * this.page
              .pageSize, this.page.currentPage * this.page.pageSize)
            this.$refs.XTable.setCurrentRow(this.dataList[this.dataList.length-1])
            this.insertSuccess = false
          }else{
            this.page.totalResult = this.defaultDataList.length
            this.dataList = this.defaultDataList.slice((this.page.currentPage - 1) * this.page
              .pageSize, this.page.currentPage * this.page.pageSize)
          }
          this.loading = false
        }, 300)
      },
    }
  }
</script>

<style lang="scss" scoped>
  .body{
    padding: 10px;
    background-color: #FFFFFF;
  }
</style>
